package com.mianyang.zhangsan.plugin.quartz.core;

import com.mianyang.zhangsan.common.constant.SecConstant;
import com.mianyang.zhangsan.common.util.StringUtils;
import com.mianyang.zhangsan.model.entity.SecIdentity;
import com.mianyang.zhangsan.plugin.mail.MailFactory;
import com.mianyang.zhangsan.plugin.mail.MailSender;
import com.mianyang.zhangsan.service.ISecIdentityService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import java.util.Map;

/**
 * 到期提醒
 * @author jiangjr
 * @date 2022-11-24
 */
@Slf4j
@Component("expireRemind")
public class ExpireRemind {
    @Autowired
    private ISecIdentityService identityService;
    @Autowired
    private MailSender mailSender;

    public void remind(Map<String, Object> param) {
        // 获取收件人
        String receive = (String) param.get("receives");
        if (StringUtils.isEmpty(receive)) {
            log.error("不存在收件人");
            throw new RuntimeException("不存在收件人");
        }
        String[] receives = receive.split(",");
        // 获取通用邮箱
        SecIdentity identity = identityService.companyMail();
        if (identity == null || StringUtils.isEmpty(identity.getRealMail()) || StringUtils.isEmpty(identity.getMailAuth())) {
            log.error("没有可用的通用邮箱");
            throw new RuntimeException("没有可用的通用邮箱");
        }
        // 获取消息体
        String message = (String) param.get("message");
        if (StringUtils.isEmpty(message)) {
            message = "你关注的任务即将到期，请注意查看~";
        }
        // 初始化邮箱
        try {
            mailSender.init(identity.getRealMail(), identity.getMailAuth());
            mailSender.sendMessage(MailFactory.simpleMail(SecConstant.MAIL_SUBJECT_EXPIRE,
                    SecConstant.MAIL_SENDER_COMPANY, message, receives));
        } catch (MessagingException e) {
            log.error("过期提醒邮件发送失败");
            throw new RuntimeException("过期提醒邮件发送失败");
        }
    }
}
